import axios, {AxiosResponse} from 'axios'
import {message} from 'ant-design-vue'
import {ACCESS_TOKEN, USER_INFO} from '@/store/mutation-types'
import {baseURL} from '@/utils/util'
import ls from '@/utils/Storage'
import {globalLoading} from '@/store/reactiveState'
import emitter from '@/utils/eventBus'

const ContentType = {
    urlencoded: 'application/x-www-form-urlencoded;charset=UTF-8',
    json: 'application/json',
    formData: 'multipart/form-data'
}

// 创建 axios 实例   withCredentials: true,
const baseService = axios.create({
    baseURL,
    timeout: 60000,
    responseType: 'json',
    headers: {
        'X-Requested-With': 'XMLHttpRequest'
    }
})

// request interceptor
baseService.interceptors.request.use(
    (config) => {
        globalLoading.value = true
        const token = ls.get(ACCESS_TOKEN)
        const userinfo = ls.get(USER_INFO)
        if (token) {
            config.headers['token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
        }
        if (userinfo) {
            config.headers['username'] = userinfo.username // 让每个请求携带自定义 token 请根据实际情况自行修改
        }
        config.headers['Content-Type'] = ContentType[config.data instanceof FormData ? 'formData' : 'json']
        return config
    },
    (error) => {
        globalLoading.value = false
        return Promise.reject(error)
    }
)

baseService.interceptors.response.use(
    (res: AxiosResponse<any>) => {
        globalLoading.value = false
        const successStatus = res.data.errCode
        const success = res.data.success
        if (successStatus && successStatus!==200) {
            message.error(res.data.errMessage)
            return Promise.reject(new Error(res.data.errMessage))
        }
        if (res.status === 200) {
            return res.data
        }
        return res.data
    },
    (error) => {
        console.log(error)
        globalLoading.value = false
        const msg = error.message
        const result = error.response
        if (result) {
            const {data, status} = result
            if (data.message || data.errMessage) {
                message.error(data.message  || data.errMessage)
            } else if (status === 401 || status === 403) {
                message.error('登录过期或权限不足, 请重新登陆!')
            } else if (status === 500) {
                message.error('请求数据失败, 请重试!')
            } else if (status === 406) {
                message.error('登陆超时请重新登录!')
                emitter.emit('axios_goto_login')
            }
        } else if (msg) {
            if (msg === 'Network Error') {
                message.error('网络错误,请检查网络!')
            } else {
                message.error(msg)
            }
        } else if (error.__CANCEL__) {
            // ignore message error
        } else {
            message.error('未知错误,请重试!')
        }

        return Promise.reject(new Error(result.data.errMessage))

        // return false
    }
)




// 发起文件下载请求
export const downloadFile = async (url, params = {}, method = 'get') => {
    try {
        // 配置请求：必须声明 responseType 为 blob/arraybuffer
        const config = {
            method,
            url,
            params: method === 'get' ? params : null,
            data: method === 'post' ? params : null,
            responseType: 'blob', // 重要：声明响应类型为二进制流
           /* onDownloadProgress: (progressEvent) => {
                const percent = Math.round(
                    (progressEvent.loaded * 100) / progressEvent.total
                );
                console.log(`下载进度：${percent}%`);
            }*/
        };

        const response = await axios(config);

        // 检查请求是否成功
        if (response.status === 200) {
            // 从响应头中提取文件名
            const fileName = getFileNameFromHeaders(response.headers);

            // 创建 Blob 对象并生成下载链接
            const blob = new Blob([response.data]);
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = fileName;
            link.click();

            // 释放临时 URL
            URL.revokeObjectURL(link.href);
        } else {
            throw new Error(`下载失败，状态码：${response.status}`);
        }
    } catch (error) {
        console.error('下载失败:', error);
        // 这里可显示错误提示（如 ElementUI 的 ElMessage）
        if (error.response?.data instanceof Blob) {
            const errorData = await error.response.data.text();
            const { message } = JSON.parse(errorData);
            message.error(`服务端错误：${message}`);
        } else {
            message.error('网络或客户端错误');
        }
    }
};

// 从响应头解析文件名
const getFileNameFromHeaders = (headers) => {
    // 优先从 Content-Disposition 头提取文件名
    const disposition = headers['content-disposition'];
    if (disposition) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(disposition);
        if (matches?.[1]) {
            return decodeURIComponent(matches[1].replace(/['"]/g, ''));
        }
    }

    // 兜底默认文件名
    return `file_${new Date().getTime()}`;
};

export default baseService
